package com.dhx.service;

import com.dhx.dao.RuKuDetailDao;

import com.dhx.dao.RuKuMainDao;
import com.dhx.model.KuCun;
import com.dhx.model.RuKuDetail;
import com.dhx.model.RuKuMain;
import com.dhx.util.DbUtil;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;

/**
 * @ClassName RuKuService
 * @Author 邓皓轩
 * @Date 2024/11/3 下午5:38
 **/
public class RuKuService {
    private RuKuDetailDao ruKuDetailDao = new RuKuDetailDao();
    private RuKuMainDao ruKuMainDao = new RuKuMainDao();
    private KuCunService kuCunService = new KuCunService();
    public boolean addRuKu(RuKuMain ruku){
        Connection conn = DbUtil.getConn();
        try {
            conn.setAutoCommit(false);
            int i = ruKuMainDao.addRuKuMain(ruku, conn);
            if (i > 0){
                ArrayList<RuKuDetail> rukudetailList = ruku.getRukudetailList();
                for (RuKuDetail detail : rukudetailList) {
                    detail.setRukuId(i);
                    boolean b = ruKuDetailDao.addRuKuDetail(detail, conn);
                    if (!b){
                        conn.rollback();
                        return false;
                    }
                    //商品添加到库存
                    KuCun kuCunByName = kuCunService.getKuCunByName(detail.getSpName(), conn);
                    if (kuCunByName == null){
                        //仓库没有
                        KuCun kuCun = new KuCun();
                        kuCun.setNum(detail.getNum());
                        kuCun.setSpname(detail.getSpName());
                        boolean b1 = kuCunService.addKuCun(kuCun, conn);
                        if (!b1){
                            conn.rollback();
                            return false;
                        }
                    }else {
                        int num = kuCunByName.getNum() + detail.getNum();
                        kuCunByName.setNum(num);
                        boolean b2 = kuCunService.updateKuCun(kuCunByName, conn);
                        if (!b2){
                            conn.rollback();
                            return false;
                        }
                    }
                }
                conn.commit();
                conn.setAutoCommit(true);
                return true;
            }else{
                conn.rollback();
                return false;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return false;
    }

    public ArrayList<RuKuMain> getRuKuList(RuKuMain ruku){
        return ruKuMainDao.getRuKuMainByName(ruku);
    }

    public Boolean updateRuKu(RuKuMain ruKuMain) {
        return ruKuMainDao.updateRuKu(ruKuMain);
    }
}
